import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../stores'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: 'Home',
      component: () => import('../views/Home.vue')
    },
    {
      path: '/products',
      name: 'Products',
      component: () => import('../views/Products.vue')
    },
    {
      path: '/products/:id',
      name: 'ProductDetail',
      component: () => import('../views/ProductDetail.vue'),
      props: true
    },
    {
      path: '/category/:id',
      name: 'Category',
      component: () => import('../views/Category.vue'),
      props: true
    },
    {
      path: '/admin/products',
      name: 'AdminProducts',
      component: () => import('../views/admin/ProductsManage.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/admin/users',
      name: 'AdminUsers',
      component: () => import('../views/admin/UsersManage.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/admin/cart',
      name: 'AdminCart',
      component: () => import('../views/admin/CartManage.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/admin/categories',
      name: 'AdminCategories',
      component: () => import('../views/admin/CategoriesManage.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/profile',
      name: 'Profile',
      component: () => import('../views/Profile.vue')
    },
    {
      path: '/cart',
      name: 'Cart',
      component: () => import('../views/Cart.vue')
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('../views/Login.vue')
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  if (to.meta.requiresAuth && !userStore.isLoggedIn) {
    // 需要登录但没有登录，重定向到首页
    next({ name: 'Home' })
  } else {
    next()
  }
})

export default router

